/**
 *  ward @ 2019
 *  harrydeep@wardyan.top
 */
package top.wardyan.tool;

import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;

import org.apache.log4j.Logger;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.TableItem;
import org.eclipse.wb.swt.SWTResourceManager;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;

import top.wardyan.base.action.BaseShell;
import top.wardyan.base.config.Const;
import top.wardyan.base.config.DataConfig;
import top.wardyan.base.util.swt.Msg;
import top.wardyan.tool.po.Conf;
import top.wardyan.tool.po.ConfItem;

/**
 * 配置管理器 - 管理 用于设置要在配置管理器中设置哪些信息
 * @author ward
 *
 * 2019年2月17日
 */
public class AppConfigProperties extends BaseShell<AppConfigProperties>{
	
	protected Logger log = Logger.getLogger(this.getClass());
	
	protected String filename = "AppConfig.properties";
	
	protected Properties prop = null;	
	protected Label lblTitle;
	protected Label lblClassification;
	protected Label lblItems;
	protected Table tblConf;
	protected Table tblItems;
	protected Label label;
	protected Button btnNewConf;
	protected Button btnNewItem;
	
	//protected Map<String, String> confs = new HashMap<>();
	protected List<Conf> confs = new ArrayList<>();
	protected Map<Conf, List<ConfItem>> items = new HashMap<>();
	protected Button btnWrite;
	
	protected void load() {
		
		File file = new File(filename);
		
		if(!file.exists())
			try {
				file.createNewFile();
			} catch (IOException e1) {
				log.error(e1);
			}
		
		try (FileReader reader = new FileReader(filename)){
			prop = new Properties();
			prop.load(reader);
			
			if(prop.get("classification") != null) {
				List<Conf> confs = JSONArray.parseArray(prop.getProperty("classification"), Conf.class);
				self.confs = confs;
				if(confs != null) {
					for(Conf c : confs) {
						List<ConfItem> items = JSONArray.parseArray(prop.getProperty("classification_" + c.getPrefix()), ConfItem.class);
						self.items.put(c, items);
					}
				}
			}
			self.listConf();
		} catch (IOException e) {
			log.error(e);
		}
	}
	
	protected void save() {
		
	}
	
	public AppConfigProperties(){
		super();
		createContents();
		load();
	}
	private void createContents() {
		//setSize(1024, 720);
		
		
		this.lblTitle = new Label(this, SWT.NONE);
		this.lblTitle.setBounds(0, 0, this.getSize().x, 50);
		this.lblTitle.setFont(Const.FONT_H5);
		this.lblTitle.setText("配置项目管理器");
		this.lblTitle.setAlignment(SWT.CENTER);
		this.lblTitle.setBackground(Const.COLOR_WHITE);
		
		
		this.lblClassification = new Label(this, SWT.NONE);
		this.lblClassification.setBounds(10, 56, 34, 23);
		this.lblClassification.setText("项目");
		this.lblClassification.setFont(Const.FONT_H8);
		this.lblClassification.setBackground(Const.COLOR_WHITE);
		
		this.lblItems = new Label(this, SWT.NONE);
		this.lblItems.setText("明细");
		this.lblItems.setFont(SWTResourceManager.getFont("新宋体", 12, SWT.NORMAL));
		this.lblItems.setBackground(SWTResourceManager.getColor(255, 255, 255));
		this.lblItems.setBounds(360, 56, 32, 16);
		
		this.tblConf = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		this.tblConf.addMouseListener(new MouseAdapter() {
			@SuppressWarnings("unchecked")
			@Override
			public void mouseDoubleClick(MouseEvent event) {
				super.mouseDoubleClick(event);
				TableItem[] itemList =tblConf.getItems();
				int listHaveChouse = tblConf.getSelectionIndex();
				String key = "conf";
				if(listHaveChouse > -1) {
					new AppConfigPropertiesConf(key, itemList[listHaveChouse].getText(1), itemList[listHaveChouse].getText(2)).go();;
					Map<String, String> cs = (Map<String, String>) DataConfig.remove(key);
					if(cs != null)
						for(Conf c : self.confs) {
							if(c.getName().equals(cs.get("name"))) {
								if(cs.get("prefix") != null && cs.get("prefix").length() > 0)
									c.setPrefix(cs.get("prefix"));
								else
									self.confs.remove(c);
								break;
							}
						}
				}
				
				self.listConf();
			}

			@Override
			public void mouseUp(MouseEvent e) {
				super.mouseUp(e);
				self.listItems();
			}
			
		});
		this.tblConf.setBounds(10, 84, 300, this.getSize().y - 130);
		this.tblConf.setHeaderVisible(true);
		this.tblConf.setLinesVisible(true);
		
		TableColumn col = new TableColumn(this.tblConf, SWT.NONE);
		col.setWidth(0);
		col.setText("");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblConf, SWT.NONE);
		col.setWidth(150);
		col.setText("标签");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblConf, SWT.NONE);
		col.setWidth(140);
		col.setText("前缀");
		col.setAlignment(SWT.CENTER);
		
		this.tblItems = new Table(this, SWT.BORDER | SWT.FULL_SELECTION);
		this.tblItems.addMouseListener(new MouseAdapter() {
			@Override
			public void mouseDoubleClick(MouseEvent event) {
				Conf conf = null;
				TableItem[] itemList =tblConf.getItems();
				int listHaveChouse = tblConf.getSelectionIndex();
				if(listHaveChouse > -1) {
					String name = itemList[listHaveChouse].getText(1);
					//ConfItem items = null;
					for(Conf c : self.confs) {
						if(c.getName().contentEquals(name)) {
							conf = c;
							break;
						}	
					}
				}
				if(conf != null) {
					List<ConfItem> items = self.items.get(conf);
					ConfItem item = null;
					if(items != null) {
						TableItem[] tblItemList = tblItems.getItems();
						int itemSelected = tblItems.getSelectionIndex();
						//new AppConfigPropertiesConf(key, itemList[listHaveChouse].getText(1), itemList[listHaveChouse].getText(2)).go();;
						if(itemSelected > -1) {
							for(ConfItem it : items) {
								if(it.getName().contentEquals(tblItemList[itemSelected].getText(1))) {
									item = it;
									break;
								}
							}
							if(item != null) {
								new AppConfigPropertiesConfItem(items, item).go();
								self.items.put(conf, items);
							}
						}
						
					}
				}
				
				
				
				self.listItems();
			}
		});
		this.tblItems.setLinesVisible(true);
		this.tblItems.setHeaderVisible(true);
		this.tblItems.setBounds(360, 84, this.getSize().x - 390, this.getSize().y - 130);
		
		col = new TableColumn(this.tblItems, SWT.NONE);
		col.setWidth(0);
		col.setText("");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblItems, SWT.NONE);
		col.setWidth(150);
		col.setText("标签");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblItems, SWT.NONE);
		col.setWidth(150);
		col.setText("代码");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblItems, SWT.NONE);
		col.setWidth(100);
		col.setText("长度");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblItems, SWT.NONE);
		col.setWidth(100);
		col.setText("必需");
		col.setAlignment(SWT.CENTER);
		
		col = new TableColumn(this.tblItems, SWT.NONE);
		col.setWidth(100);
		col.setText("加密");
		col.setAlignment(SWT.CENTER);
		
		
		this.label = new Label(this, SWT.NONE);
		this.label.setText(">>");
		this.label.setFont(SWTResourceManager.getFont("新宋体", 12, SWT.NORMAL));
		this.label.setBackground(SWTResourceManager.getColor(255, 255, 255));
		this.label.setBounds(330, 413, 16, 16);
		
		this.btnNewConf = new Button(this, SWT.NONE);
		this.btnNewConf.addSelectionListener(new SelectionAdapter() {
			@SuppressWarnings("unchecked")
			@Override
			public void widgetSelected(SelectionEvent e) {
				String key = "conf";
				new AppConfigPropertiesConf(key).go();
				Map<String, String> cs = (Map<String, String>) DataConfig.remove(key);
				if(cs != null)
					self.confs.add(new Conf(cs.get("name"), cs.get("prefix")));
				self.listConf();
			}
		});
		this.btnNewConf.setBounds(50, 56, 48, 27);
		this.btnNewConf.setText("新项目");
		
		this.btnNewItem = new Button(this, SWT.NONE);
		this.btnNewItem.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent e) {
				ConfItem newItem = new ConfItem();
				TableItem[] itemList =tblConf.getItems();
				int listHaveChouse = tblConf.getSelectionIndex();
				//new AppConfigPropertiesConf(key, itemList[listHaveChouse].getText(1), itemList[listHaveChouse].getText(2)).go();;
				if(listHaveChouse > -1) {
					String confName = itemList[listHaveChouse].getText(1);
					Conf conf = null;
					for(Conf c : self.confs) {
						if(c.getName().contentEquals(confName)) {
							conf = c;
							break;
						}	
					}
					if(conf != null) {
						new AppConfigPropertiesConfItem(newItem).go();
						if(newItem != null) {
							List<ConfItem> items = self.items.get(conf);
							if(items == null)
								items = new ArrayList<>();
							items.add(newItem);
							self.items.put(conf, items);
						}
					}
				}
				self.listItems();
			}
		});
		this.btnNewItem.setText("新明细");
		this.btnNewItem.setBounds(412, 56, 48, 27);
		
		this.btnWrite = new Button(this, SWT.NONE);
		this.btnWrite.addSelectionListener(new SelectionAdapter() {
			@Override
			public void widgetSelected(SelectionEvent event) {
				self.prop.setProperty("classification", JSONObject.toJSONString(self.confs));
				for(Conf c : self.confs) {
					self.prop.setProperty("classification_" + c.getPrefix(), JSONObject.toJSONString(self.items.get(c)));
				}
				try(FileWriter writer = new FileWriter(filename)){
					//self.prop.save(writer, "");
					self.prop.store(writer, "配置文件配置");
					Msg.showMessage("操作结果", "保存成功");
				}catch(Exception e) {
					log.error(e);
					Msg.showMessage("操作结果", "保存失败:" + e.getMessage());
				}
				
				
			}
		});
		this.btnWrite.setText("写入配置");
		this.btnWrite.setBounds(262, 56, 60, 27);
	}
	
	
	/** 检查输入. 默认检查必填项是否已填. 如果检查返回false,则断点不再执行保存 **/
	protected Boolean check() {
		Boolean rs = true;
		
		return rs;
	}
	

	protected void listConf() {
		tblConf.removeAll();
		for(Conf c : confs) {
			TableItem item = new TableItem(tblConf, SWT.NONE);
			item.setText(new String[] {
					null, c.getName(), c.getPrefix()
			});
		}
	}
	
	protected void listItems() {
		TableItem[] itemList =tblConf.getItems();
		int listHaveChouse = tblConf.getSelectionIndex();
		//new AppConfigPropertiesConf(key, itemList[listHaveChouse].getText(1), itemList[listHaveChouse].getText(2)).go();;
		if(listHaveChouse > -1) {
			String confName = itemList[listHaveChouse].getText(1);
			Conf conf = null;
			for(Conf c : self.confs) {
				if(c.getName().contentEquals(confName)) {
					conf = c;
					break;
				}	
			}
			if(conf != null) {
				tblItems.removeAll();
				List<ConfItem> items = self.items.get(conf);
				if(items != null && items.size() > 0)
					for(ConfItem it : items) {
						TableItem item = new TableItem(tblItems, SWT.NONE);
						item.setText(new String[] {
								"", it.getName(), it.getCode(), it.getMaxLength().toString(), it.getRequired().toString(), it.getEncoded().toString()
						});
					}
			}
		}	
	}
	
	
	
	
	
	public static void main(String[] args) {
		
			new AppConfigProperties().go();
	}
}
